<?php

namespace app\merchant\controller;

use app\common\model\SystemMsg;
use app\common\model\MessageOrder;
use app\common\model\MessageConsult;
use think\Db;
use think\Request;

class Message extends Common
{
    public $messageOrder;
    public $messageConsult;

    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->messageOrder = new MessageOrder();
        $this->messageConsult = new MessageConsult();
    }

    public function systemmessage()
    {
        // 系统消息
        $data = SystemMsg::GetMSG(25);

        //print_r($data);exit;
        $read_ids = Db('message_read_record')
            ->where('merchant_id', session('merchant.merchant_id'))
            ->field('message_id')->group('message_id')->select();

        $ids_map = [];
        if ($read_ids) {
            foreach ($read_ids as $id) {
                $ids_map[$id['message_id']] = $id['message_id'];
            }
        }

        $systemMessage = [];
        foreach ($data as $k => $v) {
            $v['is_read'] = 0;
            if (isset($ids_map[$v['message_id']])) {
                $v['is_read'] = 1;
            }
            $systemMessage[] = $v;
        }
        //print_r($systemMessage);exit;

        return view('systemmessage', [
            'systemMessage' => $systemMessage,
            'data' => $data
        ]);
    }

    public function ordermessage()
    {
        $pagesize = (int)$this->request->request('DataTables_Table_0_length', 25);
        // 订单消息
        $orderInfo = SystemMsg::GetOrderMSG($pagesize);
        return view('ordermessage', [
            'orderInfo' => $orderInfo,
        ]);
    }

    /**
     * 全部订单消息标为已阅读
    */
    public function readAll(){
        $res = Db::name('message_order')->where("is_read = 0")->update(['is_read' => 1]);
        if($res !== false){
            return returnJson(1, '标记成功', '');
        }else{
            return returnJson(0, '标记失败', '');
        }
    }

    public function usermessage()
    {
        $pagesize = (int)$this->request->request('DataTables_Table_0_length', 25);
        // 用户留言
        $data = Db::name('message_consult')->alias('m')
            ->join(
                '(SELECT max(id) mid FROM message_consult where to_id='.session('merchant.merchant_id').' and `type`=1 group by from_id) c',
                'm.id=c.mid'
            )
            ->join('user u', 'm.from_id=u.user_id', 'left')
            ->where('m.to_id', session('merchant.merchant_id'))
            ->where('m.type', 1)
            ->field('u.nickname, m.from_id, m.content, m.create_time, m.id, m.is_read')
            ->order('m.id desc')
            ->paginate($pagesize);

        $userMessage = [];
        foreach ($data as $k => $v) {
//            $apply = Db::name('message_consult')->where('target_id', $v['id'])->field('content, create_time')->select();
//            $applyContent = [];
//            $applyTime = [];
//            if (!empty($apply)) {
//                foreach ($apply as $value) {
//                    $applyContent[] = $value['content'];
//                    $applyTime[] = date('Y-m-d H:i:s', $value['create_time']);
//                }
//            }
//            $v['apply'] = implode("<br />", $applyContent);
//            $v['apply_time'] = implode("<br />", $applyTime);
            $userMessage[] = $v;
        }

        return view('usermessage', [
            'userMessage' => $userMessage,
            'data' => $data
        ]);
    }

    public function showlist()
    {
        $pagesize = (int)$this->request->request('DataTables_Table_0_length', 25);
        // 系统消息
        $systemMessage = SystemMsg::GetMSG($pagesize);
        // 订单消息
        $orderInfo = SystemMsg::GetOrderMSG($pagesize);
        // 用户留言
        $data = Db::name('message_consult')->alias('m')
            ->join('user u', 'm.from_id=u.user_id')
            ->where('m.to_id', session('merchant.merchant_id'))
            ->where('m.type', 1)
            ->field('u.nickname, m.from_id, m.content, m.create_time, m.id')
            ->order('m.id desc')
            ->paginate($pagesize);
        $userMessage = [];
        foreach ($data as $k => $v) {
            $apply = Db::name('message_consult')->where('target_id', $v['id'])->field('content, create_time')->select();
            $applyContent = [];
            $applyTime = [];
            if (!empty($apply)) {
                foreach ($apply as $value) {
                    $applyContent[] = $value['content'];
                    $applyTime[] = date('Y-m-d H:i:s', $value['create_time']);
                }
            }
            $v['apply'] = implode("<br />", $applyContent);
            $v['apply_time'] = implode("<br />", $applyTime);
            $userMessage[] = $v;
        }
        return view('showlist', [
            'userMessage' => $userMessage,
            'orderInfo' => $orderInfo,
            'systemMessage' => $systemMessage
        ]);
    }

    // 回复留言
    public function reply()
    {
        $msgId = input('post.msgId');
        $content = input('post.content');
        $merchant = session('merchant.merchant_id');
        $storeId = Db::name('store')->where('store_merchant_id', $merchant)->value('store_id');
        $toId = Db::name('message_consult')->where('id', $msgId)->value('from_id');
        $res = Db::name('message_consult')->insert(['store_id' => $storeId, 'from_id' => $merchant,
            'to_id' => $toId, 'content' => $content, 'type' => 2, 'target_id' => $msgId, 'create_time' => time()]);
        if ($res) {
            return returnJson(1, '回复成功', '');
        }
        return returnJson(0, '回复失败', '');
    }

    /**
     * @todo ajax检测订单message和用户message是否有未读消息
     * @return json_array
     */
    public function checkMessageRead()
    {
        //获取未读订单信息
        $messageOrder = $this->messageOrder->GetMessageUnread();
        if ($messageOrder) {
            $unreadOrder = true;
        } else {
            $unreadOrder = false;
        }
        //获取未读用户信息
        $messageConsult = $this->messageConsult->GetMessageUnread();
        if ($messageConsult) {
            $unreadConsult = true;
        } else {
            $unreadConsult = false;
        }
        return returnJson(1,'获取信息成功',['unreadOrder' => $unreadOrder, 'unreadConsult' => $unreadConsult]);
    }

    /**
     * @todo ajax设置订单已读
     * @return json_array
     */
    public function readOrderMessage()
    {
        $res = $this->messageOrder->update(['is_read' => 1],['merchant_id' => session('merchant.merchant_id'),'type' => 1,'is_read' => 0]);
        if ($res) {
            return returnJson(1, '已读成功', '');
        } else {
            return returnJson(0, '已读失败', '');
        }
    }

    /**
     * @todo ajax设置用户已读
     * @return json_array
     */
    public function readUserMessage()
    {
        $res = $this->messageConsult->update(['is_read' => 1],['to_id' => session('merchant.merchant_id'),'type' => 1,'is_read' => 0]);
        if ($res) {
            return returnJson(1, '已读成功', '');
        } else {
            return returnJson(0, '已读失败', '');
        }
    }
}
